/**
 * 
 */
package de.cbf.cam.dsa.tavern.carte.ui.listeners;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Collection;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Text;

/**
 * @author Stefan Alter
 *
 */
public class EnterPositiveDoubleForEvent implements ModifyListener,VerifyListener{
	private Composite 	compositeParent = null;
	private Collection<ActionListener> eventListeners = null;  
	
	/**
	 * 
	 */
	public EnterPositiveDoubleForEvent(Composite parent,Collection<ActionListener> eventListeners) {
		super();
		this.compositeParent = parent;
		this.eventListeners = eventListeners;
	}
		
	public static void addToText(Text text,Collection<ActionListener> eventListeners){
		EnterPositiveDoubleForEvent listener = 
			new EnterPositiveDoubleForEvent(text.getParent(), eventListeners); 
		text.addModifyListener(listener);
		text.addVerifyListener(listener);
	}
	
	@Override
	public void modifyText(ModifyEvent e) { 
		boolean priceCorrect = false;
		if (e.widget instanceof Text) {
			Text text = (Text) e.widget;
			text.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));
			if( ! text.getText().equals("")){
				try{
					Double value = Double.parseDouble(text.getText());
					if(value >= 0){
						priceCorrect = true;
					}
				}catch (NumberFormatException exc){
					priceCorrect = false;
				}			
			}else{
				priceCorrect = true;
			}
			if(priceCorrect){
				ActionEvent event = new ActionEvent(compositeParent, ActionEvent.ACTION_PERFORMED, "priceModified");
				for (ActionListener listener : eventListeners) {
					listener.actionPerformed(event);
				}
			}else{
				text.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_RED));
			}			
		}		
	}	
	@Override
	public void verifyText(VerifyEvent e) {
		if(e.text.length()> 1 || ".1234567890\b".contains(e.text)){
			e.doit = true;
		}else{
			e.doit = false;
		}			
	}

	

	
}
